jQuery(document).ready(function($) {
   if($("#summarylist").length > 0) {
      $.ajax({
         type: 'GET',
         url: OC.filePath('company', 'ajax', 'getsummary.php'),
         cache: false,
         success: function(data) {
            $("#summarylist").fadeOut("fast", function() { 
               $("#summarylist").html(data).show();
               resizeAppHeight();
            });
         }
      });
   }

   $(".closediv").click(function(){
      $(this).closest('.popup').hide();
   });

   $(".set_pdomain").not(".notvalidated").on("click", function() {
      var target = $(this);
      $("#hr_setdomain").show().position({
         my:"left top+10",
         at:"left-50 bottom",
         of:target,
         collision:"none"
      });
   });
   
   $("a.howtoaccept").click(function(){
      var target = $(this);
      $("#hr_howtoconfig").show().position({
         my:"left top+10",
         at:"left-60 bottom",
         of:target,
         collision:"none"
      });
   });
   
   jQuery("#copybtn").click(function() {
      var msg=$("#forwardemail").text();
      if(window.clipboardData){
         if(window.clipboardData.setData("Text",msg)){
            showMessagePanel("<div style='text-align:center;'>已成功复制到剪贴板!</div>", $(this), false, {placement:'bottom',timeout:5000});
         }
      }else {
         showMessagePanel("您使用的浏览器不支持此复制功能,请使用Ctrl+C或鼠标右键", $(this), false, {placement:'bottom',timeout:5000});
      } 
   });
   
   var validator = {
      rules: {
         sub_domain: {
            remote: {url: validatesubdomainurl, type: "POST"}
         }
      },
      errorPlacement: function(error,element) {  
         $(".domainbtn .error").jobUtil('showError', error);
      },
      submitHandler: function(form) {
         $(form).ajaxSubmit({
            dataType: "json",
            beforeSubmit: function(data, form, options) {
               if(!showLoading(form, options, null, {button:true}))
                  return false;
               $(".domainbtn .error", form).hide();
            },
            success: function(data) {
               try {
                  var retmsg = data;
                  if(retmsg.error) {                     
                     $(".domainbtn .error", form).jobUtil('showError', retmsg.error);
                     $("#setdomainform #sub_domain").val('');                     
                  }
                  else if(retmsg.success) {
                     $(".error", form).jobUtil('showSuccess', retmsg.success,function(){
                        var subdomain = $("#setdomainform #sub_domain").val();
                        $(".hr_netaddress #hr_setdomain").fadeOut(3000);
                        $(".hr_netaddress .set_pdomain.medium").fadeOut(3000);
                        var html = '<a id="homelink" target="_blank" href="http://'+subdomain+'.'+serverDomain+'">http://'+subdomain+'.'+serverDomain+'</a>';
                        $(".hr_netaddress #homelink").html(html);
                     }); 
                  }
               } catch(e) {
                    return false;
                 }
            }
         });
      }
   };

   $("#setdomainform").validate(validator);
   
   $('#sync_click_51job, #sync_click_zhilian, #sync_click_lagou, #sync_click_jiancai').click(function(){
      var target = $(this);

      // disable for status change 
      if(target.hasClass('ppp_whitebtn'))
         return false; 

      var data = {
         type: target.data("type"),
         syncaction: target.data("syncaction"),
         autofetchon: target.data("autofetchon"),
         vid: target.data("vid")
      }; 

      startSync(target.data("type"), data, function(submitted) {
         target.tooltip('destroy');
         if(typeof(submitted)!='undefined' && submitted){
            target.removeClass('ppp_bluebtn').addClass('ppp_whitebtn').attr('title','职位同步中，请稍后').html('同步中...');
            if(target.closest('.synch_tablelist').length > 0) {
               target.css('marginLeft','-15px');
            }
            target.parent().children('i').hide(); 
         }        
         target.tooltip(); 
      })
      return false;
   });
   
   var bstro = $("#showbootstro_cpy");
   var introDone = function() {
      storageSet("introstep_"+bstro.data('vid'),'done');
      $("#apps").css("position","fixed");
      $(".navbar-fixed-top").css("position","fixed");
      $("#apps").css("zIndex",75);
      $(".bootstro-backdrop").css("zIndex",1050);
      $(".navbar-fixed-top").css("zIndex",1030);
   };
   
   var checkIdx = function(idx) {
      switch(idx) {
         case 1:
         case 3:
            $(".bootstro-backdrop").css("zIndex",1039);
            break;
         case 2:
            $(".navbar-fixed-top").css("zIndex","auto");
            break;
         case 4:
         case 5:
         case 6:
            $("#apps").css("zIndex","auto");
            break;
         case 7:
            $(".bootstro-finish-btn").show();
            break;
         case 0:
         default:
            break;
      }

      // in any step, we need to trigger modal dialog or menu list hide 
      $(".modal").modal("hide");
      $("#psysnotify").trigger("hidetasklist");
   };
      
   if(window.bootstro && ((bstro.hasClass("first_register") || typeof(storageGet("introstep_"+bstro.data('vid'))) != "undefined") && storageGet("introstep_"+bstro.data('vid')) != 'done')){
      //新手引导的时候，将顶部和左边竖排的nav菜单改为absolute定位。
      $("#apps").css("position","absolute");
      $(".navbar-fixed-top").css("position","absolute");
      
      //取出每一个需要做介绍的target赋值上一个特殊的class
      $("#companycenter i.bstro_approve").addClass("b_introclass0");
      $(".hr_netaddress .synchronous_info").eq(0).addClass("b_introclass1");
      $("#psysnotify").addClass("b_introclass2");
      $(".hr_netaddress .synchronous_info").eq(1).addClass("b_introclass3");
      $("#apps a").eq(1).addClass("b_introclass4");
      $("#apps a").eq(3).addClass("b_introclass5");
      $("#apps a").eq(5).addClass("b_introclass6");
      $(".hr_companystep .hr_c_6").addClass("b_introclass7");
      
      //新手引导功能开始调用
      bootstro.start("",{
         nextButton : '<button class="btn btn-small bootstro-next-btn">继续 »</button>',
         prevButton : '<button class="btn btn-small bootstro-prev-btn">上一步 «</button>',
         finishButton : '<button class="ppp_bluebtn btn btn-mini bootstro-finish-btn" style="display:none;">开始使用云招聘</button>',
         items : [{selector:".b_introclass0","step":"0","placement":"bottom","width":"400px","title":"新用户向导","content":"请上传您公司的最新年检的营业执照副本，通过验证后即可使用云招聘功能。"},
                  {selector:".b_introclass1","step":"1","placement":"bottom","width":"320px","title":"新用户向导","content":"与第三方招聘网站信息同步，点击“同步职位”按钮开始同步。"},
                  {selector:".b_introclass2","step":"2","placement":"bottom","width":"195px","title":"新用户向导","content":"在顶部的“通知”菜单可查看同步进度。"},
                  {selector:".b_introclass3","step":"3","placement":"bottom","width":"400px","title":"新用户向导","content":"同步成功后，灰色“√”图标会变为绿色。"},
                  {selector:".b_introclass4","step":"4","placement":"right","width":"400px","title":"新用户向导","content":"同步完成后，您即可在“职位管理”中管理职位，设置匹配条件，笔试和评测。"},
                  {selector:".b_introclass5","step":"5","placement":"right","width":"400px","title":"新用户向导","content":"挑选到合适的人才后，您可以安排面试，管理日程，云招聘自动按时发送短信及邮件提醒。"},
                  {selector:".b_introclass6","step":"6","placement":"right","width":"400px","title":"新用户向导","content":"您可以在账户设置中创建子账号，协同管理招聘，子帐号可指定职位和权限。"},
                  {selector:".b_introclass7","step":"7","placement":"top","width":"400px","title":"新用户向导","content":"云招聘更多详细功能介绍，请点击这里查看。"}],
         onStep : function(params)
            {  
               storageSet("introstep_"+bstro.data('vid'),params.idx+1);
               checkIdx(params.idx);
            },
         onExit : function() { 
            introDone();
         },
         onComplete : function() { 
            introDone();
         }
      });
      
      //重新加载页面的时候，跳转到上次的步骤
      currstep = storageGet("introstep_"+bstro.data('vid'));
      if(!currstep) {
         currstep = 0;
         storageSet("introstep_"+bstro.data('vid'),1);
      }  
      else 
         currstep = parseInt(currstep);
      
      if(currstep != 0) {
         bootstro.go_to(currstep-1);
         checkIdx(currstep-1);
      }
};

   $(document).on('click','#showevent a',function(){
      var target = $(this);
      var id = target.attr('data-eventid');
      var share = $('#fullcalendar').attr('data-share');
      var userid = $('#fullcalendar').attr('data-userid');
      var type = 'home';
      
      $.ajax({
         type: "GET",
         url: OC.filePath('calendar', 'ajax/event', 'preview.php'),
         data: {id: id, share: share, userid: userid, type: type},
         dataType: 'html',
         cache: false,
         success: function(data) {
            if (!isLoggedIn(data, target)) {
               window.location = login_url;
               return false;
            }
            if ( data == 'No events found.' ) {
               showMessagePanel(t('calendar', 'No events found.'), target, true, {placement:'top'});
               return false;
            }
            $('#preview_holder').html(data).show().position({
               my: "left top",
               at: "left bottom",
               of: target
            });
            $("#preview_holder .contentline_each a").tooltip();
         }
      });
      return false;
   });

   $(document).bind('keydown', function(event) {
      if(event.keyCode == 27) {
         $(".popup").not('.keepopen').hide();
         return true;
      }
   });

   $(document).bind('mousedown', function(e){
      e = $.event.fix(e);
      var otarget = $(e.target);
      if(otarget.closest(".popup").length>0) {
         if(otarget.hasClass("close")) {
            otarget.closest(".popup").hide();
            return true;
         }
         return true;
      }
      // close all popup 	
      $(".popup").not('.keepopen').hide();
      return true;
   });
   
   $("#validate_note").each(function(){
      $(this).position({
         my: "left+5 top-7",
         at: "right top",
         of: $(".hr_companycenter_name h4 i")
      });
   });
   
   $(document).on('click','#collection',function(){
      var value=0;
      var target = $(this);
      if(target.is(':checked')==true){
         value=1;
      }
      $.ajax({
         type:"POST",
         url:OC.filePath('company', 'ajax', 'jobsaved.php'),
         data:{collect:value},
         beforeSend: function() {
            if(!showLoading(target))
               return false;
         },
         success:function(result){
            if(!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }      
            if(result.status === 'success') {
               //window.location.reload();
               var url = getUrlQuery(OC.filePath('jobposition', 'ajax', 'getjoblist.php')) + '&nocache=' + Math.random(); 
               var target = $("#joblist .list-footer:first");
               $.ajax({
                  url: url,
                  beforeSend: function(xhr, settings) {
                     showLoading(target, settings, null, {button:true});
                  },
                  success: function(data) {
                     jQuery("#joblist").fadeOut("fast", function() { 
                        jQuery("#joblist").html(data).fadeIn(); 
                     }); 
                  }
               });
            }else if(result.error) {
               showMessagePanel(result.error, target, true, {placement:'left'});
            }
        }
      })
   })   
}); 
